import random
import time

from sqlalchemy import and_

from exts import db
from flask import Blueprint, request, Response, jsonify, render_template, url_for, redirect, session
import json

from class_room.model import Class_Room
from student.model import Student
from user.model import User

class_room = Blueprint('class_room', __name__);

# 班级列表
@class_room.route('class_room_list', methods=['GET', 'POST'])
def class_room_list():
    class_room_list = Class_Room.query.all()
    return render_template('class_room_list.html', class_room_list=class_room_list)

# 班级搜索
@class_room.route('/class_room/search', methods=['GET', 'POST'])
def search():
    keyword = request.args.get('keyword')
    class_room_list = Class_Room.query.filter(
        Class_Room.class_name.like('%{keyword}%'.format(keyword=keyword))
    ).all()
    return render_template('class_room_list.html', class_room_list=class_room_list)

# 删除班级
@class_room.route('/class_room/remove', methods=['GET', 'POST'])
def remove():
    id = request.args.get('id')
    class_room = Class_Room.query.filter(
        Class_Room.id == id
    ).first()
    db.session.delete(class_room)
    db.session.commit()
    return redirect(url_for('class_room.class_room_list'))

# 班级详情，编辑，更新，添加
@class_room.route('/class_room/edit', methods=['GET', 'POST'])
def edit():
    if request.method=='GET':
        id = request.args.get('id')
        option = request.args.get('option')
        class_room = Class_Room.query.filter(
            Class_Room.id == id
        ).first()
        if option == 'detail':
            return render_template('class_room_editor.html', class_room=class_room) 
        else:
            return render_template('class_room_editor.html', class_room=class_room, update=True)
    else:
        id = request.form.get('id')
        class_name = request.form.get('class_name')
        teacher_name = request.form.get('teacher_name')
        student_number = request.form.get('student_number')

        class_room = Class_Room.query.filter(
            Class_Room.id == id
        ).first()
        if class_room is None:
            class_room = Class_Room(class_name=class_name, teacher_name=teacher_name, student_number=student_number)
            db.session.add(class_room)
            db.session.commit()
        else:
            class_room.class_name = class_name
            class_room.teacher_name = teacher_name
            class_room.student_number = student_number
            db.session.commit()
        return redirect(url_for("class_room.class_room_list"))